package xml.resource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.commons.dbutils.DbUtils;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.ResourceException;
import xml.hcard.HCARDFactory;
import xml.hcard.LocalHCARDFactory;
import xml.model.Adresse;
import xml.model.Contact;
import xml.model.Email;
import xml.model.Telephone;
import xml.model.Type;
import xml.validator.LongRangeValidator;

/**
 * Resource représentant la représentation hCard d'un contact.
 * Méthodes: GET
 * @author marya
 */
public class ContactHCARDResource extends AbstractResource {

    private Contact contact;

    public ContactHCARDResource() {
        super();
    }

    @Override
    protected void doInit() throws ResourceException {
        Long idContact;
        Connection connexion = null;
        final String sqlContact = "SELECT * FROM contact WHERE id_contact = ";
        final String sqlTel = "SELECT tel.value, type.libelle FROM tel "
                + "INNER JOIN type ON type.id_type = tel.id_type "
                + "WHERE tel.id_contact = ";
        final String sqlEmail = "SELECT email.value, type.libelle FROM email "
                + "INNER JOIN type ON type.id_type = email.id_type "
                + "WHERE email.id_contact = ";
        String idContactAttribute = getRequest().getAttributes().get("idContact").toString();
        LongRangeValidator longRangeValidator = new LongRangeValidator(1l, null);
        if (longRangeValidator.isValid(idContactAttribute)) {
            idContact = Long.parseLong(idContactAttribute);
        } else {
            throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "invalidIdContact");
        }

        try {
            connexion = database.getNewConnection();
            ResultSet rs = connexion.createStatement().executeQuery(sqlContact + idContact);
            if (rs != null && rs.next()) {
                contact = new Contact(
                        rs.getString("nom"),
                        rs.getString("prenom"),
                        new Adresse(
                        rs.getString("voie"),
                        rs.getString("ville"),
                        rs.getString("code_postal"),
                        rs.getString("pays")));
                contact.setIdContact(rs.getInt("id_contact"));
                rs = connexion.createStatement().executeQuery(sqlTel + idContact);
                while (rs.next()) {
                    contact.getTels().add(new Telephone(Type.getType(rs.getString("libelle")), rs.getString("value")));
                }
                rs = connexion.createStatement().executeQuery(sqlEmail + idContact);
                while (rs.next()) {
                    contact.getEmails().add(new Email(Type.getType(rs.getString("libelle")), rs.getString("value")));
                }
                DbUtils.closeQuietly(rs);
                DbUtils.closeQuietly(connexion);
                contact.setUri(getRootRef().getHostIdentifier() + "/contacts/" + contact.getIdContact());
            } else {
                DbUtils.closeQuietly(connexion);
                setExisting(false);
            }

        } catch (SQLException e) {
            DbUtils.rollbackAndCloseQuietly(connexion);
            throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
        }
    }

    @Get
    public Representation doGet() throws Exception {
        HCARDFactory hF = new LocalHCARDFactory(null, contact.toXML());
        return hF.start().toXML();
    }
}
